package cn.org.itool.ws.framework.netty.channel;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import lombok.extern.log4j.Log4j2;

/**
 * 关闭WebSocket消息处理
 *
 */
@ChannelHandler.Sharable
@Log4j2
public class CloseHandler extends SimpleChannelInboundHandler<CloseWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CloseWebSocketFrame frame) {
        if(ctx.channel().isActive()){
            if(log.isDebugEnabled()){
                log.debug("Read ws close frame channelId={}, code={}",
                        ctx.channel().id().asLongText(), frame.statusCode());
            }
            ctx.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if(log.isErrorEnabled()){
            log.error("Close ws fail channelId={}, throw={}",
                    ctx.channel().id().asLongText(), cause.getMessage());
        }
        if(ctx.channel().isActive()){
            ctx.channel().close();
        }
    }
}
